package com.hk.blog.controller;

import com.hk.blog.constants.PermissionConstant;
import com.hk.blog.domain.UserInfo;
import com.hk.blog.service.RoleService;
import com.hk.blog.service.UserInfoService;
import com.hk.blog.service.UserRoleService;
import com.hk.blog.vo.UserRoleBean;
import com.hk.commons.JsonResult;
import com.hk.commons.query.Order;
import com.hk.core.jdbc.query.ConditionQueryModel;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;


/**
 * @author Kevin
 */
@RestController
@RequestMapping("user")
@RequiredArgsConstructor
public class UserInfoController {

    private final UserInfoService userInfoService;

    private final UserRoleService userRoleService;

    private final RoleService roleService;

    @PostMapping("list")
    @PreAuthorize(value = "hasAuthority('" + PermissionConstant.USER_LIST + "')")
    public JsonResult<?> userList(@RequestBody ConditionQueryModel query) {
        return JsonResult.success(userInfoService.queryForPage(query));
    }

    @PostMapping("updaterole")
    public JsonResult<?> updateRole(@RequestBody UserRoleBean body) {
        userRoleService.updateRole(body);
        return JsonResult.success();
    }

    @PostMapping("role/{userId}")
    public JsonResult<?> findUserRole(@PathVariable Long userId) {
        return JsonResult.success(Map.of(
                "roleIds", userRoleService.findRoleIdByUserId(userId),
                "roles", roleService.findAll(Order.desc("lastModifiedDate")).stream()
                        .map(item ->
                                Map.of("key", Objects.requireNonNull(item.getId()), "title",
                                        String.format("(%s) - (%s)", item.getRoleCode(), item.getRoleName()))
                        ).toList()));
    }

    @GetMapping("get")
    @PreAuthorize(value = "hasAuthority('" + PermissionConstant.USER_GET + "')")
    public JsonResult<?> get(@RequestParam(value = "id", required = false) Long id) {
        return JsonResult.success(userInfoService.findById(id));
    }

    @PostMapping("delete")
    @PreAuthorize(value = "hasAuthority('" + PermissionConstant.USER_DELETE + "')")
    public JsonResult<?> deleteById(@RequestParam(value = "id") Long id) {
        userInfoService.deleteById(id);
        return JsonResult.success();
    }

    @PostMapping("save")
    @PreAuthorize(value = "hasAuthority('" + PermissionConstant.USER_SAVE_OR_UPDATE + "')")
    public JsonResult<?> saveOrUpdate(@RequestBody UserInfo userInfo) {
        userInfoService.insertOrUpdate(userInfo);
        return JsonResult.success();
    }

}




